<?php
class Listing_Form_PostAnAddResidentialForm extends Listing_Form_PostAnAddForm
{
    private $_preview_link = '';

    private $_category;
    private $_adid;
    private $_listing;

    protected $elementButtonDecorators = array(
        'ViewHelper',
        'Errors',
    );

    protected $elementDecorators = array(
        'ViewHelper',
    );

    protected $formDecorators = array(
        'PrepareElements',
        array('ViewScript', array('viewScript' => 'index/customization/residential-post-an-ad.phtml'))
    );

    protected $subFormDecorators = array(
        'FormElements',
        array('Description', array('placement' => 'prepend')),
        'fieldset',
    );

    protected $spanDecorators = array(
        'ViewHelper',
        'Errors',
        array('Label', array('placement' => 'prepend')),
        array(array('row' => 'HtmlTag'), array('tag' => 'span')),
    );

    protected $displayGroupDecorators = array(
        'FormElements',
        array('HtmlTag', array('tag' => 'p', 'class' => 'price radio text')),
        array('Description', array('placement' => 'prepend', 'tag' => 'label')),
    );

    protected $elementCheckBoxDecorators = array(
        'ViewHelper',
        'Errors',
        array('Label', array('placement' => 'APPEND')),
        array(array('row' => 'HtmlTag'), array('tag' => 'span')),
    );

    protected $elementMultiCheckBoxDecorators = array(
        'ViewHelper',
        'Errors',
    );

    public function __construct($options = array())
    {
        $this->_preview_link = !empty($options['preview_link']) ? $options['preview_link'] : '';
        $this->_category = !empty($options['category']) ? $options['category'] : array();
        $this->_adid = !empty($options['adid']) ? $options['adid'] : array();
        $this->_listing = !empty($options['listing']) ? $options['listing'] : new StdClass();
        parent::__construct();
    }
    
    public function init()
    {
        parent::init();

        /*
        $this->addElement('text', 'category0', array(
            'filters'    => array('StringTrim'),
            'validators' => array(
            ),
            'required'   => false,
        ));

        $this->getElement('category0')->setValue((string)$this->_category[0]);

        var_dump((string)$this->_category[0]);
        */
        $element = new Zend_Form_Element_Hidden('adid');
        $element->setValue((string) $this->_adid);
        $element->setDecorators(array(
                'ViewHelper'
            )
        );
        $this->addElement($element);
        
        $i = 0;
        
        foreach($this->_category  as $cat) {
            $i++;
            $element = new Zend_Form_Element_Hidden('category_link'.$i);
            $element->setValue((string) $cat->_id);
            $element->setDecorators(array(
                    'ViewHelper'
                )
            );
            $this->addElement($element);
        }
        $cat_str = '<ul>';
        foreach ($this->_category as $cat_id) {
            $cat_str .= '<li>';
            $tmp = array();
            $category = Model_Category::find($cat_id->_id);
            foreach ($category->getParentTree() as $cat) {
                $tmp[] = $cat->name;
            }
            $cat_str .= implode(' > ', $tmp);
            $cat_str .= '</li>';
        }
        $cat_str .= '</ul>';
        $this->setDescription($cat_str);
        
/*
        $this->addElement('hidden', 'category1', array(
            'filters'    => array('StringTrim'),
            'validators' => array(
            ),
            'value' => (string)$this->_category[0],
            'required'   => false,
        ));
*/
        //$this->getElement('category1')->setValue((string)$this->_category[0]);


        //Title
        $this->addElement('text', 'tl_en', array(
            'validators' => array(
                array('NotEmpty', true, array('messages' => '星号栏必须填写')),
            ),
            'decorators' => $this->elementDecorators,
            'required'   => true,
        ));

        /*/Sale By
        $this->addElement('radio', 'agency_owner', array(
            'filters'    => array('StringTrim', 'StringToLower'),
            'validators' => array(
                'Int'
            ),
            'multiOptions' => array(
                '1' => 'Agency',
                '0' => 'Owner',
            ),
            'separator' => '',
            'value' => '0',
            'disableLoadDefaultDecorators' => true,
            'decorators' => $this->elementDecorators,
            'required'   => false,
        ));
        
        $this->addElement('checkbox', 'sole_agency', array(
            'filters'    => array('StringTrim', 'StringToLower'),
            'validators' => array(
            ),
            'disableLoadDefaultDecorators' => true,
            'decorators' => $this->elementDecorators,
            'required'   => false,
        ));*/


        /**********************************************************
         *                          AGENT
         *********************************************************/
        /*$this->addElement('text', 'agent_name', array(
            'filters'    => array('StringTrim', 'StringToLower'),
            'validators' => array(
                array('NotEmpty', true, array('messages' => 'This information is required')),
            ),
            'disableLoadDefaultDecorators' => true,
            'decorators' => $this->elementDecorators,
            'required'   => false,
        ));
        
        $this->addElement('text', 'agent_phone', array(
            'filters'    => array('StringTrim', 'StringToLower'),
            'validators' => array(
                array('Int', true, array('messages' => 'Numbers Only')),
            ),
            'disableLoadDefaultDecorators' => true,
            'decorators' => $this->elementDecorators,
            'required'   => false,
        ));

        $this->addElement('text', 'agent_id', array(
            'filters'    => array('StringTrim', 'StringToLower'),
            'validators' => array(
                array('Int', true, array('messages' => 'Numbers Only')),
            ),
            'disableLoadDefaultDecorators' => true,
            'decorators' => $this->elementDecorators,
            'required'   => false,
        ));

        $this->addElement('text', 'agent_email', array(
            'filters'    => array('StringTrim', 'StringToLower'),
            'validators' => array(
                array('NotEmpty', true, array('messages' => 'This information is required')),
                array('EmailAddress', true, array('messages' => 'Valid Email required')),
            ),
            'disableLoadDefaultDecorators' => true,
            'decorators' => $this->elementDecorators,
            'required'   => true,
        ));/*

        /**********************************************************
         *                          PRICE
         *********************************************************/
        $this->addElement('text', 'sale_price', array(
            'filters'    => array('StringTrim', 'StringToLower'),
            'validators' => array(
                array('Int', true, array('messages' => '仅能填写数字')),
                array('NotEmpty', true, array('messages' => '请填写售价或租价')),
            ),
            'disableLoadDefaultDecorators' => true,
            'decorators' => $this->elementDecorators,
            'required'   => false,
        ));

        /*$this->addElement('checkbox', 'price_negotiable', array(
            'filters'    => array('StringTrim', 'StringToLower'),
            'validators' => array(
            ),
            'disableLoadDefaultDecorators' => true,
            'decorators' => $this->elementDecorators,
            'required'   => false,
        ));

        $this->addElement('hidden', 'add_more_checkbox', array(
            'filters'    => array('StringTrim', 'StringToLower'),
            'validators' => array(
            ),
            'disableLoadDefaultDecorators' => true,
            'value' => '1',
            'decorators' => array(
                'ViewHelper',
                'Errors',
                array(array('data' => 'HtmlTag'), array('style' => 'display:none')),
            ),
            'required'   => false,
        ));

        $this->addElement('checkbox', 'sale_lease', array(
            'filters'    => array('StringTrim', 'StringToLower'),
            'validators' => array(
            ),
            'disableLoadDefaultDecorators' => true,
            'decorators' => $this->elementDecorators,
            'required'   => false,
        ));

        $this->addElement('datePicker', 'lease_enddate', array(
           'jQueryParams' => array(
               'defaultDate' => time(),
               'dateFormat'  => 'dd/mm/yy'
           ),
           //'disableLoadDefaultDecorators' => true,
           //'decorators' => $this->elementDecorators,
           'required'   => false,
        ));
        $this->getElement('lease_enddate')->removeDecorator('label');


        $this->addElement('text', 'current_lease_price', array(
            'filters'    => array('StringTrim', 'StringToLower'),
            'validators' => array(
                array('Float', true, array('messages' => 'Numbers Only')),
            ),
            'disableLoadDefaultDecorators' => true,
            'decorators' => $this->elementDecorators,
            'required'   => false,
        ));

        $this->addElement('checkbox', 'rent_property_too', array(
            'filters'    => array('StringTrim', 'StringToLower'),
            'validators' => array(
            ),
            'disableLoadDefaultDecorators' => true,
            'decorators' => $this->elementDecorators,
            'required'   => false,
        ));*/

        $this->addElement('text', 'rent_price', array(
            'filters'    => array('StringTrim', 'StringToLower'),
            'validators' => array(
                array('Int', true, array('messages' => '仅能填写数字')),
                array('NotEmpty', true, array('messages' => '请填写售价或租价')),
            ),
            'disableLoadDefaultDecorators' => true,
            'decorators' => $this->elementDecorators,
            'required'   => false,
        ));

        /*$this->addElement('checkbox', 'rent_include_mngt_fee', array(
            'filters'    => array('StringTrim', 'StringToLower'),
            'validators' => array(
            ),
            'disableLoadDefaultDecorators' => true,
            'decorators' => $this->elementDecorators,
            'required'   => false,
        ));*/

        /**********************************************************
         *                          LOCATION
         *********************************************************/
        $areas = Model_Location::getAreaL1PostAd();
        if (empty($_POST['area_l1'])) {
            $selected_area = 0;
            if (!empty($this->_listing)) {
                $selected_area = '';
                if (empty($selected_area)) {
                    $loc = $this->_listing->area_l2;
                    if (!empty($loc)) {
                        $selected_area = (string)$loc->getParent()->_id;
                    }
                }
            }
        }
        else {
            $selected_area = $_POST['area_l1'];
        }
        if (empty($selected_area)) {
            reset($areas);
            $selected_area = key($areas);
        }
        $this->addElement('select', 'area_l1', array(
            'filters'    => array('StringTrim'),
            'validators' => array(
                array('NotEmpty', true, array('messages' => '请在下拉菜单选择一个选项，不能为空')),
            ),
            'multiOptions' => $areas,
            'disableLoadDefaultDecorators' => true,
            'decorators' => $this->elementDecorators,
            'required'   => true,
        ));

        //District
        $this->addElement('select', 'area_l2', array(
            'filters'    => array('StringTrim'),
            'validators' => array(
                array('NotEmpty', true, array('messages' => '请在下拉菜单选择一个选项，不能为空')),
            ),
            'multiOptions' => Model_Location::getAreaL2PostAd($selected_area),
            'disableLoadDefaultDecorators' => true,
            'decorators' => $this->elementDecorators,
            'required'   => false,
        ));
        //$this->getElement('area_l2')->setOptions(array('disabled'=>'disabled'));
        
        //location flag
        $this->addElement('radio', 'loc_flag', array(
            'filters'    => array('StringTrim', 'StringToLower'),
            'validators' => array(
                //'Int'
            ),
            'multiOptions' => array(
                'chi' => '中国+香港+澳门',
                'mchi' => '中国大陆',
            ),
            'separator' => '',
            //'value' => '0',
            'disableLoadDefaultDecorators' => true,
            'decorators' => $this->elementDecorators,
            'required'   => false,
        ));
        
        
		$this->addElement('select', 'rent_type', array(
            'validators' => array(
                array('NotEmpty', true, array('messages' => '请在下拉菜单选择一个选项，不能为空')),
            ),
            'multiOptions' => Model_Listing_Residential::getRentTypePostAd(),
            'disableLoadDefaultDecorators' => true,
            'decorators' => $this->elementDecorators,
            'required'   => true,
        ));
        
        $this->addElement('select', 'bedroom', array(
            'filters'    => array('StringTrim', 'StringToLower'),
            'validators' => array(
                //array('NotEmpty', true, array('messages' => 'This information is required')),
                array('Int', true, array('messages' => '仅能填写数字')),
            ),
            'multiOptions' => Model_Listing_Residential::getBedroomPostAd(),
            'disableLoadDefaultDecorators' => true,
            'decorators' => $this->elementDecorators,
            'required'   => false,
        ));

		$this->addElement('select', 'other_room', array(
            'filters'    => array('StringTrim', 'StringToLower'),
            'validators' => array(
            	array('Int', true, array('messages' => '仅能填写数字')),
                //array('NotEmpty', true, array('messages' => 'This information is required')),
            ),
            'multiOptions' => Model_Listing_Residential::getOtherRoomPostAd(),
            'disableLoadDefaultDecorators' => true,
            'decorators' => $this->elementDecorators,
            'required'   => false,
        ));
        
        $this->addElement('select', 'bathroom', array(
            'filters'    => array('StringTrim', 'StringToLower'),
            'validators' => array(
            	array('Int', true, array('messages' => '仅能填写数字')),
                //array('NotEmpty', true, array('messages' => 'This information is required')),
            ),
            'multiOptions' => Model_Listing_Residential::getToiletPostAd(),
            'disableLoadDefaultDecorators' => true,
            'decorators' => $this->elementDecorators,
            'required'   => false,
        ));
		
		$this->addElement('text', 'which_floor', array(
            'filters'    => array('StringTrim', 'StringToLower'),
            'validators' => array(
            	array('Int', true, array('messages' => '仅能填写数字')),
                //array('NotEmpty', true, array('messages' => 'This information is required')),
            ),
            //'multiOptions' => Model_Listing_Residential::getBedroomPostAd(),
            'disableLoadDefaultDecorators' => true,
            'decorators' => $this->elementDecorators,
            'required'   => false,
        ));
        
        $this->addElement('text', 'total_floor', array(
            'filters'    => array('StringTrim', 'StringToLower'),
            'validators' => array(
            	array('Int', true, array('messages' => '仅能填写数字')),
                //array('NotEmpty', true, array('messages' => 'This information is required')),
            ),
            //'multiOptions' => Model_Listing_Residential::getBedroomPostAd(),
            'disableLoadDefaultDecorators' => true,
            'decorators' => $this->elementDecorators,
            'required'   => false,
        ));
        
        $this->addElement('text', 'age', array(
            'filters'    => array('StringTrim', 'StringToLower'),
            'validators' => array(
            	array('Int', true, array('messages' => '仅能填写数字')),
                //array('NotEmpty', true, array('messages' => 'This information is required')),
            ),
            //'multiOptions' => Model_Listing_Residential::getBedroomPostAd(),
            'disableLoadDefaultDecorators' => true,
            'decorators' => $this->elementDecorators,
            'required'   => false,
        ));
        
        $this->addElement('text', 'total_size', array(
            'filters'    => array('StringTrim', 'StringToLower'),
            'validators' => array(
            	
                //array('NotEmpty', true, array('messages' => 'This information is required')),
                array('Int', true, array('messages' => '仅能填写数字')),
            ),
            'disableLoadDefaultDecorators' => true,
            'decorators' => $this->elementDecorators,
            'required'   => false,
        ));
        
		// Direction
        $this->addElement('multiCheckbox', 'direction', array(
            'validators' => array(
                //'EmailAddress',
            ),
            'multioptions' => Model_Listing_Residential::getDirections(),
            'disableLoadDefaultDecorators' => true,
            'decorators' => $this->elementMultiCheckBoxDecorators,
            'required'   => false,
        ));
        
        $this->addElement('text', 'size', array(
            'filters'    => array('StringTrim', 'StringToLower'),
            'validators' => array(
                //array('NotEmpty', true, array('messages' => 'This information is required')),
                array('Int', true, array('messages' => '仅能填写数字')),
            ),
            'disableLoadDefaultDecorators' => true,
            'decorators' => $this->elementDecorators,
            'required'   => false,
        ));
        
        $this->addElement('select', 'renovation', array(
            'filters'    => array('StringTrim', 'StringToLower'),
            'validators' => array(
            	array('Int', true, array('messages' => '仅能填写数字')),
                //array('NotEmpty', true, array('messages' => 'This information is required')),
            ),
            'multiOptions' => Model_Listing_Residential::getRenovationPostAd(),
            'disableLoadDefaultDecorators' => true,
            'decorators' => $this->elementDecorators,
            'required'   => false,
        ));

        /*$this->addElement('select', 'bathroom', array(
            'validators' => array(
                //'Float'
            ),
            'multiOptions' => Model_Listing_Residential::getBathroomPostAd(),
            'disableLoadDefaultDecorators' => true,
            'decorators' => $this->elementDecorators,
            'required'   => false,
        ));


        $this->addElement('select', 'building_age', array(
            'filters'    => array('StringTrim', 'StringToLower'),
            'validators' => array(
                'Int'
            ),
            'multiOptions' => Model_Listing_Residential::getBuildingAgePostAd(),
            'disableLoadDefaultDecorators' => true,
            'decorators' => $this->elementDecorators,
            'required'   => false,
        ));

        $this->addElement('select', 'building_type', array(
            'validators' => array(
            ),
            'multiOptions' => Model_Listing_Residential::getBuildingTypePostAd(),
            'disableLoadDefaultDecorators' => true,
            'decorators' => $this->elementDecorators,
            'required'   => false,
        ));

        $this->addElement('select', 'floor_zone', array(
            'validators' => array(
            ),
            'multiOptions' => Model_Listing_Residential::getFloorZonePostAd(),
            'disableLoadDefaultDecorators' => true,
            'decorators' => $this->elementDecorators,
            'required'   => false,
        ));*/

        $this->addElement('textarea', 'cs_en', array(
            'filters'    => array('StringTrim'),
            'validators' => array(
                array('NotEmpty', true, array('messages' => '星号栏必须填写')),
            ),
            'decorators' => $this->elementDecorators,
            'rows'=>'',
            'required'   => true,
        ));

        /*$this->addElement('textarea', 'st_en', array(
            'filters'    => array('StringTrim'),
            'validators' => array(
                array('NotEmpty', true, array('messages' => 'This information is required')),
            ),
            'decorators' => $this->elementDecorators,
            'rows'=>'',
            'required'   => true,
        ));
*/
		$this->addElement('text', 'st_en', array(
       	 	'filters'    => array('StringTrim'),
            'validators' => array(
                //array('NotEmpty', true, array('messages' => 'This information is required')),                
            ),
            'decorators' => $this->elementDecorators,
            'required'   => false,
            'label'      => 'Street address:',
        ));
        
        $this->addElement('text', 'complex', array(
            'validators' => array(
                //array('NotEmpty', true, array('messages' => 'This information is required')),                
            ),
            'decorators' => $this->elementDecorators,
            //'decorators' => array_merge($this->elementDecorators, array(array(array('row' => 'HtmlTag'), array('tag' => 'p', 'class' => 'title text')))),
            'required'   => false,
            'label'      => 'Complex:',
        ));
      //  echo '<pre>';
      //  print_r($this);exit;

        /*$this->addElement('select', 'location', array(
            'filters'    => array('StringTrim'),
            'validators' => array(
                'Alnum',
                array('StringLength', false, 24),
            ),
            'multiOptions' => array(
              1 => '', 'Free', 'Contact'
            ),
            'decorators' => $this->elementDecorators,
            'required'   => false,
            'label'      => 'Location:',
        ));


        $this->addElement('text', 'street', array(
            'filters'    => array('StringTrim'),
            'validators' => array(
            ),
            'decorators' => $this->elementDecorators,
            'required'   => false,
            'label'      => 'Street address:',
        ));

        $this->addElement('text', 'management_fee', array(
            'filters'    => array('StringTrim', 'StringToLower'),
            'validators' => array(
                array('Float', true, array('messages' => 'Numbers Only')),
            ),
            'disableLoadDefaultDecorators' => true,
            'decorators' => $this->elementDecorators,
            'required'   => false,
        ));

        $this->addElement('text', 'government_fee', array(
            'filters'    => array('StringTrim', 'StringToLower'),
            'validators' => array(
                array('Float', true, array('messages' => 'Numbers Only')),
            ),
            'disableLoadDefaultDecorators' => true,
            'decorators' => $this->elementDecorators,
            'required'   => false,
        ));

        $this->addElement('text', 'oth_en', array(
            'filters'    => array('StringTrim', 'StringToLower'),
            'validators' => array(
                //'Int'
            ),
            'disableLoadDefaultDecorators' => true,
            'decorators' => $this->elementDecorators,
            'required'   => false,
        ));

        // Facilities
        $this->addElement('multiCheckbox', 'facilities', array(
            'validators' => array(
                //'EmailAddress',
            ),
            'multioptions' => Model_Listing_Residential::getFacilities(),
            'disableLoadDefaultDecorators' => true,
            'decorators' => $this->elementMultiCheckBoxDecorators,
            'required'   => false,
        ));

        // View
        $this->addElement('multiCheckbox', 'views', array(
            'validators' => array(
                //'EmailAddress',
            ),
            'multioptions' => Model_Listing_Residential::getViews(),
            'disableLoadDefaultDecorators' => true,
            'decorators' => $this->elementMultiCheckBoxDecorators,
            'required'   => false,
        ));

        // Rooms
        $this->addElement('multiCheckbox', 'rooms', array(
            'validators' => array(
                //'EmailAddress',
            ),
            'multioptions' => Model_Listing_Residential::getRooms(),
            'disableLoadDefaultDecorators' => true,
            'decorators' => $this->elementMultiCheckBoxDecorators,
            'required'   => false,
        ));

        // Outdoor
        $this->addElement('multiCheckbox', 'outdoor', array(
            'validators' => array(
                //'EmailAddress',
            ),
            'multioptions' => Model_Listing_Residential::getOutdoor(),
            'disableLoadDefaultDecorators' => true,
            'decorators' => $this->elementMultiCheckBoxDecorators,
            'required'   => false,
        ));

        // Layout
        $this->addElement('multiCheckbox', 'layout', array(
            'validators' => array(
                //'EmailAddress',
            ),
            'multioptions' => Model_Listing_Residential::getLayout(),
            'disableLoadDefaultDecorators' => true,
            'decorators' => $this->elementMultiCheckBoxDecorators,
            'required'   => false,
        ));

        // Conditions
        $this->addElement('multiCheckbox', 'conditions', array(
            'validators' => array(
                //'EmailAddress',
            ),
            'multioptions' => Model_Listing_Residential::getConditions(),
            'disableLoadDefaultDecorators' => true,
            'decorators' => $this->elementMultiCheckBoxDecorators,
            'required'   => false,
        ));*/
        
        
        
        $this->addElement('text', 'tag', array(
            'validators' => array(
                //array('NotEmpty', true, array('messages' => 'This information is required')),                
            ),
            'decorators' => $this->elementDecorators,
            //'decorators' => array_merge($this->elementDecorators, array(array(array('row' => 'HtmlTag'), array('tag' => 'p', 'class' => 'title text')))),
            'required'   => false,
            'label'      => 'Tag:',
        ));
        
        $this->addElement('text', 'remark', array(
            'validators' => array(
                //array('NotEmpty', true, array('messages' => 'This information is required')),                
            ),
            'decorators' => $this->elementDecorators,
            //'decorators' => array_merge($this->elementDecorators, array(array(array('row' => 'HtmlTag'), array('tag' => 'p', 'class' => 'title text')))),
            'required'   => false,
            'label'      => 'Remark:',
        ));
        
        $this->addElement('text', 'c_name', array(
            'validators' => array(
                //array('NotEmpty', true, array('messages' => 'This information is required')),                
            ),
            'decorators' => $this->elementDecorators,
            //'decorators' => array_merge($this->elementDecorators, array(array(array('row' => 'HtmlTag'), array('tag' => 'p', 'class' => 'title text')))),
            'required'   => false,
            'label'      => 'Contact Name:',
        ));
        
        $this->addElement('checkbox', 'agent', array(
            'filters'    => array('StringTrim', 'StringToLower'),
            'validators' => array(
            ),
            'disableLoadDefaultDecorators' => true,
            'decorators' => $this->elementDecorators,
            'required'   => false,
        ));
        
        $this->addElement('text', 'c_tel', array(
            'validators' => array(
                //array('NotEmpty', true, array('messages' => 'This information is required')),                
            ),
            'decorators' => $this->elementDecorators,
            //'decorators' => array_merge($this->elementDecorators, array(array(array('row' => 'HtmlTag'), array('tag' => 'p', 'class' => 'title text')))),
            'required'   => false,
            'label'      => 'Contact Tel:',
        ));
        
        $this->addElement('text', 'c_msn', array(
            'validators' => array(
                //array('NotEmpty', true, array('messages' => 'This information is required')),                
            ),
            'decorators' => $this->elementDecorators,
            //'decorators' => array_merge($this->elementDecorators, array(array(array('row' => 'HtmlTag'), array('tag' => 'p', 'class' => 'title text')))),
            'required'   => false,
            'label'      => 'MSN / QQ:',
        ));
        
        $this->addElement('button', 'validate', array(
            'required'    => false,
            'ignore'      => true,
            'type'        => 'submit',
            'label'       => 'Post your ad',
            'decorators'  => array_merge($this->elementButtonDecorators, array(array(array('row' => 'HtmlTag'), array('tag' => 'p', 'class' => 'button_em')))),
        ));

        $this->addElement('button', 'preview', array(
            'required'    => false,
            'ignore'      => true,
            'type'        => 'button',
            'label'       => 'Preview',
            //'description' => '<a href="'.$this->_preview_link.'">Preview</a>',
            'decorators'  => array_merge($this->elementButtonDecorators, array(array(array('row' => 'HtmlTag'), array('tag' => 'p', 'class' => 'preview button')))),
        ));


        $opt = $this->getDecorator('ViewScript')->getOptions();
        $opt['category'] = $this->_category;
        $opt['adid'] = $this->_adid;
        $opt['listing'] = $this->_listing;
        $opt['preview_link'] = $this->_preview_link;

        $this->getDecorator('ViewScript')->setOptions($opt);

    }

    public function populate(array $arr)
    {
        //echo "<PRE>";
        //print_r($this->_listing);
        //exit;
        //
    // Required
        //Title
        // if (empty($arr['title'])) {
            // $this->getElement('title')->setValue($this->_listing->title);
        // }
        //Description
        // if (empty($arr['description'])) {
            // $this->getElement('description')->setValue($this->_listing->description);
        // }
		
		if (Zend_Registry::get('current_language') == 'en'){
			$ft = 'en';
			$tt = 'zh-TW';
			
            $this->getElement('tl_en')->setValue($this->_listing->tl_en);
			$this->getElement('cs_en')->setValue($this->_listing->cs_en);
			//$this->getElement('oth_en')->setValue($this->_listing->oth_en);
			$this->getElement('st_en')->setValue((string)$this->_listing->st_en);
			
			
		} else {
			$ft = 'zh-TW';
			$tt = 'en';
			
			$this->getElement('tl_en')->setValue($this->_listing->tl_sc);
            $this->getElement('cs_en')->setValue($this->_listing->cs_sc);
            $this->getElement('st_en')->setValue((string) $this->_listing->st_sc);
			
		}
		
        //Price
        if(empty($arr['price'])) {
            if (!empty($this->_listing->sale_price)) {
                $this->getElement('sale_price')->setValue($this->_listing->sale_price);
            }
            if (!empty($this->_listing->rent_price)) {
                $this->getElement('rent_price')->setValue($this->_listing->rent_price);
            } 
        }
        //Area
        if (empty($arr['area_l1'])) {
                $selected_area = '';
                if (empty($selected_area)) {
                    $loc = $this->_listing->area_l2;
                    if (!empty($loc)) {
                        $selected_area = (string)$loc->getParent()->_id;
                    }
                }            
            $this->getElement('area_l1')->setValue((string)$selected_area);
        }
        //District
        if (empty($arr['area_l2'])) {
            if (isset($this->_listing->area_l2->_id)) {
                $this->getElement('area_l2')->setValue((string)$this->_listing->area_l2->_id);
            }
        }
        //Street
        // if (empty($arr['street'])) {
            // $this->getElement('address')->setValue((string)$this->_listing->street);
        // }
        /*/Price Negotiable
        if (empty($arr['price_negotiable'])) {
            $this->getElement('price_negotiable')->setValue((string)$this->_listing->price_negotiable);
        }
        //Sell with lease
        if (empty($arr['sale_lease'])) {
            //var_dump($this->_listing);exit;
            $this->getElement('sale_lease')->setValue((string)$this->_listing->sale_lease);
            if ($this->_listing->sale_lease == 1) {
                //Current lease
                if (empty($arr['current_lease_price'])) {
                    $this->getElement('current_lease_price')->setValue((string)$this->_listing->current_lease_price);
                }
                //Lease End Date
                if (empty($arr['lease_enddate'])) {
                    $this->getElement('lease_enddate')->setValue((string)$this->_listing->lease_enddate);
                }
            }
        }*/
        //Rent my Property too
        if (!empty($this->_listing->rent_price)) {
            //Rent Price
            if (empty($arr['rent_price'])) {
                $this->getElement('rent_price')->setValue((string)$this->_listing->rent_price);
            }
            /*/Rent Price
            if (empty($arr['rent_include_mngt_fee'])) {
                $this->getElement('rent_include_mngt_fee')->setValue((string)$this->_listing->rent_include_mngt_fee);
            }*/
        }
        
        //rent type
        if (empty($arr['rent_type'])) {
            $this->getElement('rent_type')->setValue((string)$this->_listing->rent_type);
        }
        //Bedroom
        if (empty($arr['bedroom'])) {
            $this->getElement('bedroom')->setValue((string)$this->_listing->bedroom);
        }
        //Other room
        if (empty($arr['other_room'])) {
            $this->getElement('other_room')->setValue((string)$this->_listing->other_room);
        }
        //Toilet
        if (empty($arr['bathroom'])) {
            $this->getElement('bathroom')->setValue((string)$this->_listing->bathroom);
        }
        //renovation
        if (empty($arr['renovation'])) {
            $this->getElement('renovation')->setValue((string)$this->_listing->renovation);
        }
        if (empty($arr['complex'])) {
            $this->getElement('complex')->setValue((string)$this->_listing->complex);
        }
        //which floor
        if (empty($arr['which_floor'])) {
            $this->getElement('which_floor')->setValue((string)$this->_listing->which_floor);
        }
        //total_floor
        if (empty($arr['total_floor'])) {
            $this->getElement('total_floor')->setValue((string)$this->_listing->total_floor);
        }
        //age
        if (empty($arr['age'])) {
            $this->getElement('age')->setValue((string)$this->_listing->age);
        }
        //total_size
        if (empty($arr['total_size'])) {
            $this->getElement('total_size')->setValue((string)$this->_listing->total_size);
        }
        //Direction
        if (empty($arr['direction'])) {
            $this->getElement('direction')->setValue((array)$this->_listing->direction);
        }
        //Size
        if (empty($arr['size'])) {
            $this->getElement('size')->setValue((string)$this->_listing->size);
        }
        //agent
        if (empty($arr['agent'])) {
            $this->getElement('agent')->setValue((string)$this->_listing->agent);
        }

    /*/Optional
        //Bathroom
        if (empty($arr['bathroom'])) {
            $this->getElement('bathroom')->setValue((string)$this->_listing->bathroom);
        }
        //Building Type
        if (empty($arr['building_type'])) {
            $this->getElement('building_type')->setValue((string)$this->_listing->building_type);
        }
        //Building Age
        if (empty($arr['building_age'])) {
            $this->getElement('building_age')->setValue((string)$this->_listing->building_age);
        }
        //Floor Zone
        if (empty($arr['floor_zone'])) {
            $this->getElement('floor_zone')->setValue((string)$this->_listing->floor_zone);
        }
        //Facilities
        if (empty($arr['facilities'])) {
            $this->getElement('facilities')->setValue($this->cleanupIntKeys((array)$this->_listing->facilities));
        }
        //View
        if (empty($arr['views'])) {
            $this->getElement('views')->setValue((array)$this->_listing->views);
        }
        //Rooms
        if (empty($arr['rooms'])) {
            $this->getElement('rooms')->setValue((array)$this->_listing->rooms);
        }
        //Outdoor
        if (empty($arr['outdoor'])) {
            $this->getElement('outdoor')->setValue((array)$this->_listing->outdoor);
        }
        //Layout
        if (empty($arr['layout'])) {
            $this->getElement('layout')->setValue((array)$this->_listing->layout);
        }
        //Conditions
        if (empty($arr['conditions'])) {
            $this->getElement('conditions')->setValue((array)$this->_listing->conditions);
        }*/
        //Others
        /* if (empty($arr['other'])) {
            $this->getElement('other')->setValue((string)$this->_listing->other);
        } */
        /*/Management Fee
        if (empty($arr['management_fee'])) {
            $this->getElement('management_fee')->setValue((string)$this->_listing->management_fee);
        }
        //government Fee
        if (empty($arr['government_fee'])) {
            $this->getElement('government_fee')->setValue((string)$this->_listing->government_fee);
        }*/       
		if (empty($arr['tag'])) {
        	if(!empty($this->_listing->tags)){
				$this->getElement('tag')->setValue(implode(',', $this->_listing->tags));
			}            
        }
        
        if (empty($arr['remark'])) {
            $this->getElement('remark')->setValue((string)$this->_listing->remark);
        }
        
        if (empty($arr['c_name'])) {
            $this->getElement('c_name')->setValue((string)$this->_listing->c_name);
        }
        
        if (empty($arr['c_tel'])) {
            $this->getElement('c_tel')->setValue((string)$this->_listing->c_tel);
        }
        
        if (empty($arr['c_msn'])) {
            $this->getElement('c_msn')->setValue((string)$this->_listing->c_msn);
        }		

        parent::populate($arr);
        return $arr;
    }

    public function save($preview = false) {
        if (empty($this->_adid)) {
            $ad = new Model_Listing_Regular();
        } else {
            $ad = Model_Listing_Preview::find(new MongoId($this->_adid));
        }
        $this->_category = Model_Listing_Preview::fixCategories($this->_category);

        //print_r((string)$this->_adid);exit;
        if (Zend_Registry::isRegistered('loggedin_user')) {
            $user = Zend_Registry::get('loggedin_user');
            if ($user->role == Model_User::ROLE_ADMIN) {
                if (empty($ad->us)) {
                    $ad->user = $user->_id;
                }
            } else {
                $ad->user = $user->_id;
            }
            if (empty($this->status)) {
                $ad->status = Model_Listing::STATUS_PUBLISHED;
            }
        } else {
            $ad->status = 6;
        }
        $POST = $_REQUEST;
        //echo '<PRE>';print_r($POST);exit;
        //echo "<PRE>";var_dump($ad->category);
        //Requiered Attributs
        // $ad->title                  = $POST['title'];
        // $ad->description            = $POST['description'];
        if (!empty($POST['rent_type'])) {
            $ad->rent_type = $POST['rent_type'];
        }
        if (!empty($POST['renovation'])) {
            $ad->renovation = $POST['renovation'];
        }
        if (!empty($POST['complex'])) {
            $ad->complex = $POST['complex'];
        }
        $ad->bedroom = $POST['bedroom'];
        $ad->other_room = $POST['other_room'];
        $ad->bathroom = $POST['bathroom'];
        $ad->which_floor = $POST['which_floor'];
        $ad->total_floor = $POST['total_floor'];
        $ad->age = $POST['age'];
        $ad->total_size = $POST['total_size'];
        if (!empty($POST['direction'])) {
            $ad->direction = $this->cleanupIntKeys((array) $POST['direction']);
        }
        $ad->tl_sc 			= (string)$this->getValue('tl_en');
        $ad->cs_sc 			= (string)$this->getValue('cs_en');
        $ad->st_sc 			= (string)$this->getValue('st_en');
        //$ad->tag = (string)$this->getValue('tag');
		if (!empty($POST['tag']))         {$ad->tags         = array_values(explode(',',$POST['tag']));}
        $ad->rmrk = (string)$this->getValue('remark');
        $ad->c_name = (string)$this->getValue('c_name');
        $ad->c_tel = (string)$this->getValue('c_tel');
        $ad->c_msn = (string)$this->getValue('c_msn');
        $ad->loc_flag = (string)$this->getValue('loc_flag');
        $ad->agent = (string)$this->getValue('agent');
        

        $classname = Model_Listing::getInstanceClassname((array) $this->_listing->ca);
        $translateFields = $classname::getTranslationFormField();

        $this->translate($ad, $translateFields, $classname);

        //Temporary        
        $storage = false;
        $apartment = false;
        $house = false;
        $cats = $this->_category;
        while (list($k, $cat) = each($cats)) {
            $cat = Model_Category::find($cat);
            $cats[$k] = $cat;
            //Storage
            if (($cat->nm_en == "Storage for Sale") || ($cat->nm_en == "Storage for Rent")) {
                if ($storage) {
                    unset($this->_category[$k]);
                    continue;
                }
                $this->_category[$k]->nm_en = 'Storage';
                $storage = true;
            }
            //Apartments
            if (($cat->nm_en == "Apartments for Sale") || ($cat->nm_en == "Apartments for Rent")) {
                if ($apartment) {
                    unset($this->_category[$k]);
                    continue;
                }
                $this->_category[$k]->nm_en = 'Apartments';
                $apartment = true;
            }
            //Houses
            if (($cat->nm_en == "Houses for Sale") || ($cat->nm_en == "Houses for Rent")) {
                if ($house) {
                    unset($this->_category[$k]);
                    continue;
                }
                $this->_category[$k]->nm_en = 'Houses';
                $house = true;
            }
        }
        $this->_category = $cats;

        //
        //Ce qu'il faut faire : Lier les level 3 for sale et for rent avec le level 3 de meme niveau
        //

        //force categories
        /*
          $tmp = array();
          foreach($this->_category as $cat) {
          $tmp[] = $cat->_id;
          }
          $ad->ca = $tmp;
          $ad = Model_Listing_Preview::fixCategories($ad);
         */
        //echo "<PRE>";var_dump($this->_category, $ad);
        //Save the category related to this Ad
        $ad->ca = array();
        //echo 'category';
        //var_dump($this->_category, $ad);
        foreach ($this->_category as $cat) {
            /*
            //Storage
            if ($cat->id == 'storage') {
                //For Sale and Rent
                $sale = Model_Category::one(array('id' => 'c554'));
                $rent = Model_Category::one(array('id' => 'c553'));
                if ((!empty($POST['sale_price'])) & (!empty($POST['rent_price']))) {
                    $ad->addCategory($sale->_id);
                    $ad->addCategory($rent->_id);
                }
                //For Sale
                if ((!empty($POST['sale_price'])) & (empty($POST['rent_price']))) {
                    $ad->addCategory($sale->_id);
                }
                //For Rent
                if ((empty($POST['sale_price'])) & (!empty($POST['rent_price']))) {
                    $ad->addCategory($rent->_id);
                }
            }*/
            //Apartments
            
            if ($cat->nm_en == 'Apartments / Houses' || $cat->nm_en == 'Apartments / Houses For Sale' || $cat->nm_en == 'Apartments / Houses For Rent') {
                //For Sale and Rent
                //$sale = Model_Category::one(array('id' => 'c414'));
                //$rent = Model_Category::one(array('id' => 'c413'));
                $sale = Model_Category::one(array('id' => '779b1c22831b2a5daa2e8886656074d7')); //apartments-houses-for-sale
                $rent = Model_Category::one(array('id' => '76adeee8a239120620aa140d0804d720')); //apartments-houses-for-rent
                if ((!empty($POST['sale_price'])) & (!empty($POST['rent_price']))) {
                    $ad->addCategory($sale->_id);
                    $ad->addCategory($rent->_id);
                }
                //For Sale
                if ((!empty($POST['sale_price'])) & (empty($POST['rent_price']))) {
                    $ad->addCategory($sale->_id);
                }
                //For Rent
                if ((empty($POST['sale_price'])) & (!empty($POST['rent_price']))) {
                    $ad->addCategory($rent->_id);
                }
            }
			
			if ($cat->nm_en == 'Serviced Apartments') {
				$ad->addCategory(new MongoId('4e40b5d69ad3e56dd6c319f1'));
			}
            /*
            //Houses
            elseif ($cat->id == 'houses') {
                //For Sale and Rent
                $sale = Model_Category::one(array('id' => 'c438'));
                $rent = Model_Category::one(array('id' => 'c432'));
                if ((!empty($POST['sale_price'])) & (!empty($POST['rent_price']))) {
                    $ad->addCategory($sale->_id);
                    $ad->addCategory($rent->_id);
                }
                //For Sale
                if ((!empty($POST['sale_price'])) & (empty($POST['rent_price']))) {
                    $ad->addCategory($sale->_id);
                }
                //For Rent
                if ((empty($POST['sale_price'])) & (!empty($POST['rent_price']))) {
                    $ad->addCategory($rent->_id);
                }
            }
             
             */
        }
		// echo '<pre>';
		// print_r( $ad);
		// echo '</pre>';
		// exit;
		
        //echo "<PRE>after category";var_dump($ad);
        //exit;
        // If it is a sale
        if (!empty($POST['sale_price'])) {
            $ad->sale_price = $POST['sale_price'];
            //$ad->price_negotiable       = !empty($POST['price_negotiable']);
            //If there is a lease
            /*if ($POST['sale_lease'] == '1') {
                $ad->sale_lease = $POST['sale_lease'];
                $ad->lease_enddate = $POST['lease_enddate'];
                $ad->current_lease_price = $POST['current_lease_price'];
            } else {
                $ad->sale_lease = '';
                $ad->lease_enddate = '';
                $ad->current_lease_price = '';
            }*/
        } else {
            $ad->sale_price = '';
        }

        // If it is a rent
        if (!empty($POST['rent_price'])) {
            //$ad->rent_include_mngt_fee = $POST['rent_include_mngt_fee'];
            $ad->rent_price = $POST['rent_price'];
        } else {
            //$ad->rent_include_mngt_fee = '';
            $ad->rent_price = '';
        }

        //$ad->street                 = $POST['address'];
        $ad->size = $POST['size'];
        $ad->area_l1 = new MongoId($POST['area_l1']);
        if ((string) $_POST['area_l1'] == ONLINE_ONLY_AREA) {
            $ad->area_l2 = new MongoId(ONLINE_ONLY_AREA);
        }
        elseif((string)$this->getValue('area_l1') == ENTIRE_CITY) {
            $ad->area_l2 = new MongoId(ENTIRE_CITY);
        } else {
            $ad->area_l2 = new MongoId($_POST['area_l2']);
        }

        /*/Optional Attributs
        if (!empty($POST['bathroom'])) {
            $ad->bathroom = $POST['bathroom'];
        }
        if (!empty($POST['building_age'])) {
            $ad->building_age = $POST['building_age'];
        }
        if (!empty($POST['building_type'])) {
            $ad->building_type = $POST['building_type'];
        }
        if (!empty($POST['floor_zone'])) {
            $ad->floor_zone = $POST['floor_zone'];
        }

        if (!empty($POST['facilities'])) {
            $ad->facilities = $this->cleanupIntKeys((array) $POST['facilities']);
        }
        if (!empty($POST['views'])) {
            $ad->views = $this->cleanupIntKeys((array) $POST['views']);
        }
        if (!empty($POST['rooms'])) {
            $ad->rooms = $this->cleanupIntKeys((array) $POST['rooms']);
        }
        if (!empty($POST['conditions'])) {
            $ad->conditions = $this->cleanupIntKeys((array) $POST['conditions']);
        }
        if (!empty($POST['outdoor'])) {
            $ad->outdoor = $this->cleanupIntKeys((array) $POST['outdoor']);
        }
        if (!empty($POST['layout'])) {
            $ad->layout = $this->cleanupIntKeys((array) $POST['layout']);
        }

        if (!empty($POST['management_fee'])) {
            $ad->management_fee = $POST['management_fee'];
        }
        if (!empty($POST['government_fee'])) {
            $ad->government_fee = $POST['government_fee'];
        }
        if (!empty($POST['other'])) {
            $ad->other = $POST['oth_en'];
        }*/





        $this->continueFillup();
        if (!$preview) {
            //echo "<PRE>before save";var_dump($ad);
            $ad = Model_Listing_Preview::saveAsListing($ad);
            //echo "<PRE>";var_dump($ad);
            //exit;            
            Model_Listing_Preview::remove(array('_id' => $ad->_id));
        } else {
            //$ad = Model_Listing_Preview::convertFromListing($ad);
            $ad->forceSave();
        }
        return $ad;
    }

    protected function continueFillup()
    {

    }

    public function __toString()
    {
        $str = '
            $j("#area_l1").change(function (event) {                
                event.stopImmediatePropagation();
                $j.get("/search/get-attribute", { c:"area", f:"area_l2_postad", id: $j("#area_l1").val() },
                    function(data) {
                        $j("#area_l2").empty();
                        $j.each(data, function (index, value) {
                            $(document.createElement("option"))
                                .html(value)
                                .attr("value", index)
                                .appendTo($("#area_l2"));
                        });
                        //Entire City
					    if ($j("#area_l1").val() == "4eeae63be62d6c5978000000" || $j("#area_l1").val() == "4eeeeeeeeeeeeeeeeeeeeeee" || $j("#area_l1").val() == "4aaaaaaaaaaaaaaaaaaaaaaa") {
					        $j("#area_l2").hide();
					        $j("#st_en").hide();
					    }
					    else {
					        $j("#area_l2").show();
					        $j("#st_en").show();
					    }
                    });
           });
		   
        ';
		
		
        $this->view->JQuery()->addJavascript($str);
		
        return parent::__toString();
    }

    public function isValid($post = array())
    {
        $test1 = parent::isValid($post);
        $test2 = true;

        //Check Bad Words in Title
        if ($match = Ac_Util::checkBadWord($_POST['tl_en'])) {
            $this->getElement('tl_en')->addError('Your Ad contains banned words: '. implode(', ', $match));
            $test2 = false;
        }

        //Check Bad Words in Description
        if ($match = Ac_Util::checkBadWord($_POST['cs_en'])) {
            $this->getElement('cs_en')->addError('Your Ad contains banned words: '. implode(', ', $match));
            $test2 = false;
        }

        //Regex Title contain Email Address
        if (preg_match("#.[a-z0-9._-]+@[a-z0-9._-]{2,}\.[a-z]{2,4}.#", $_POST['tl_en'])) {
        	$this->getElement('tl_en')->addError('Remove Email');
            $test2 = false;
        }
        //Regex description contain Email Address
        if (preg_match("#.[a-z0-9._-]+@[a-z0-9._-]{2,}\.[a-z]{2,4}.#", $_POST['cs_en'])) {
            $test2 = false;
        }

        //Empty field for lease or rent if not checked        
        /*if ($post['sale_lease'] == '0') {
            $this->getElement('current_lease_price')->setValue('');
            $this->getElement('lease_enddate')->setValue('');
        }*/

        //For Sale
        /*if (!empty($post['sale_price'])) {
            if(!is_int($post['sale_price'])){
				$this->getElement('sale_price')->addError('仅能填写数字');
				$test2 = true;
			}
        }
        if (!empty($post['rent_price'])){
            if(!is_int($post['rent_price'])){
				$this->getElement('rent_price')->addError('仅能填写数字');
				$test2 = true;
			}
        } */
        //for rent
        /*if (empty($_POST['sale_price'])) {
            if (empty($_POST['rent_price'])){
                $this->getElement('sale_price')->addError(array('NotEmpty', true, array('messages' => '请填写售价或租价')));
                $this->getElement('rent_price')->addError('请填写售价或租价');
                $test2 = false;
            }            
        }*/

        //For Sale with a lease
        /*if (($post['sale_lease'] == '1') & (empty($post['sale_price']))) {
            $this->getElement('sale_price')->addError('This information is required');
            $test2 = false;
        }
        if ($post['sale_lease'] == '1') {
            if (empty($post['current_lease_price'])) {
                $this->getElement('current_lease_price')->addError('This information is required');
                $test2 = false;
            }
            if (empty($post['lease_enddate'])) {
                $this->getElement('lease_enddate')->addError('This information is required');
                $test2 = false;
            }
        }*/
        
        if(empty($_POST['sale_price']) && empty($_POST['rent_price'])){
			$test2 = false;
		}

        //Exception for Online Only for Area and District
        $data = Model_Location::one(array('_id' => new MongoId($post['area_l1'])));
        if (!empty($data)) {
            /*if ($data->nm_en != 'Online Only') {
                if (empty($post['district'])) {
                    $this->getElement('district')->addError('This information is required');
                    $test2 = false;
                }
            }*/
            if ($data->nm_sc != 'Entire City') {
                if (empty($post['area_l2'])) {
                    $this->getElement('area_l2')->addError('This information is required');
                    $test2 = false;
                }
            }
        }



        //echo "<PRE>";
        //var_dump($this->getErrors());exit;

        //Check the two validations
        if ($test1 & $test2){
            return true;
        }
        else {
            return false;
        }     
    }
}
